/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package yxt.push.org.androidpn.client;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

/**
 * This class is to notify the user of messages with NotificationManager.
 * 
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class Notifier
{

	private static final String LOGTAG = LogUtil.makeLogTag(Notifier.class);

	private static final Random random = new Random(System.currentTimeMillis());

	private Context context;

	private SharedPreferences sharedPrefs;

	private NotificationManager notificationManager;

	private SQLiteDatabase mSQLiteDatabase = null;

	public Notifier(Context context)
	{
		this.context = context;
		this.sharedPrefs = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		this.notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	public void notify(String notificationId, String apiKey, String title, String message, String uri, String notificationRemark,
			String notificationType, List<Map<String, Object>> list_type, String accountname, String mobilephone, String hospitalcode,
			String sendDate)
	{

		Log.d(LOGTAG, "notify()...");

		Log.d(LOGTAG, "notificationId=" + notificationId);
		Log.d(LOGTAG, "notificationApiKey=" + apiKey);
		Log.d(LOGTAG, "notificationTitle=" + title);
		Log.d(LOGTAG, "notificationMessage=" + message);
		Log.d(LOGTAG, "notificationUri=" + uri);
		Log.d(LOGTAG, "notificationType=" + notificationType);
		Log.d(LOGTAG, "accountname=" + accountname);
		Log.d(LOGTAG, "mobilephone=" + mobilephone);
		Log.d(LOGTAG, "hospitalcode=" + hospitalcode);
		Log.d(LOGTAG, "sendDate=" + sendDate);
		if (isNotificationEnabled())
		{
			// Show the toast
			if (isNotificationToastEnabled())
			{
				Toast.makeText(context, title, Toast.LENGTH_LONG).show();
			}
			String str = "";
			if (notificationType.equals("100"))
			{
				str = "排队提醒";
			}
			else if (notificationType.equals("200"))
			{
				str = "挂号提醒";
			}
			else if (notificationType.equals("300"))
			{
				str = "缴费提醒";
			}
			else if (notificationType.equals("301"))
			{
				str = "一日清单提醒";
			}
			else if (notificationType.equals("400"))
			{
				str = "导航提醒";
			}
			else
			{
				str = "消息提醒";
			}

			// Notification
			Notification notification = new Notification();
			notification.icon = getNotificationIcon();
			notification.defaults = Notification.DEFAULT_LIGHTS;
			if (isNotificationSoundEnabled())
			{
				notification.defaults |= Notification.DEFAULT_SOUND;
			}
			if (isNotificationVibrateEnabled())
			{
				notification.defaults |= Notification.DEFAULT_VIBRATE;
			}
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			notification.when = System.currentTimeMillis();
			notification.tickerText = str;

			Intent intent = new Intent(context, NotificationDetailsActivity.class);
			intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
			intent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
			intent.putExtra(Constants.NOTIFICATION_TITLE, title);
			intent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
			intent.putExtra(Constants.NOTIFICATION_URI, uri);
			intent.putExtra(Constants.NOTIFICATION_TYPE, notificationType);
			intent.putExtra(Constants.NOTIFICATION_REMARK, notificationRemark);
			intent.putExtra(Constants.ACCOUNTNAME, accountname);
			intent.putExtra(Constants.MOBILEPHONE, mobilephone);
			intent.putExtra(Constants.HOSPITALCODE, hospitalcode);
			intent.putExtra(Constants.SENDDATE, sendDate);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

			// PendingIntent contentIntent = PendingIntent.getActivity(context,
			// random.nextInt(),
			// intent, PendingIntent.FLAG_UPDATE_CURRENT);
			//
			// notification.setLatestEventInfo(context, title, message,
			// contentIntent);
			// notificationManager.notify(random.nextInt(), notification);
			savedata(notificationId, apiKey, title, message, uri, notificationType, accountname, mobilephone, hospitalcode,sendDate);

			for (int i = 0; i < list_type.size(); i++)
			{
				Map<String, Object> m = list_type.get(i);
				if (m.get("type").equals(notificationType))
				{
					PendingIntent contentIntent = PendingIntent.getActivity(context, i, intent, PendingIntent.FLAG_UPDATE_CURRENT);
					String messageType;
					if (m.get("type").toString().equals("100"))
					{
						messageType = "排队提醒";
					}
					else if (m.get("type").toString().equals("200"))
					{
						messageType = "挂号提醒";
					}
					else if (m.get("type").toString().equals("300"))
					{
						messageType = "缴费提醒";
					}
					else if (m.get("type").toString().equals("301"))
					{
						messageType = "一日清单提醒";
					}
					else if (m.get("type").toString().equals("400"))
					{
						messageType = "导航提醒";
					}
					else
					{
						messageType = "消息提醒";
					}
					title = messageType + "(" + getcount(m.get("type").toString(), accountname, mobilephone, hospitalcode) + "条信息)";
					// notification.setLatestEventInfo(context, title,
					// message,contentIntent);
					notification.setLatestEventInfo(context, title, "", contentIntent);
					notificationManager.notify(i, notification);
				}
			}
			// Intent clickIntent = new Intent(
			// Constants.ACTION_NOTIFICATION_CLICKED);
			// clickIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
			// clickIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
			// clickIntent.putExtra(Constants.NOTIFICATION_TITLE, title);
			// clickIntent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
			// clickIntent.putExtra(Constants.NOTIFICATION_URI, uri);
			// // positiveIntent.setData(Uri.parse((new StringBuilder(
			// // "notif://notification.adroidpn.org/")).append(apiKey).append(
			// // "/").append(System.currentTimeMillis()).toString()));
			// PendingIntent clickPendingIntent = PendingIntent.getBroadcast(
			// context, 0, clickIntent, 0);
			//
			// notification.setLatestEventInfo(context, title, message,
			// clickPendingIntent);
			//
			// Intent clearIntent = new Intent(
			// Constants.ACTION_NOTIFICATION_CLEARED);
			// clearIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
			// clearIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
			// // negativeIntent.setData(Uri.parse((new StringBuilder(
			// // "notif://notification.adroidpn.org/")).append(apiKey).append(
			// // "/").append(System.currentTimeMillis()).toString()));
			// PendingIntent clearPendingIntent = PendingIntent.getBroadcast(
			// context, 0, clearIntent, 0);
			// notification.deleteIntent = clearPendingIntent;
			//
			// notificationManager.notify(random.nextInt(), notification);

		}
		else
		{
			Log.w(LOGTAG, "Notificaitons disabled.");
		}
	}

	public String getcount(String type, String accountname, String mobilephone, String hospitalcode)
	{
		String count = "";
		try
		{
			mSQLiteDatabase = context.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", context.MODE_PRIVATE, null);
			String select = " select count(*) as c from WX_PUSH where type='" + type + "' and accountname ='" + accountname
					+ "' and mobilephone='" + mobilephone + "' and hospitalcode='" + hospitalcode + "' and isshow='0' ";
			Cursor cursor = mSQLiteDatabase.rawQuery(select, null);
			// 将光标移动到下一行，从而判断该结果集是否还有下一条数据，如果有则返回true，没有则返回false

			if (cursor != null && cursor.getCount() >= 0)
				while (cursor.moveToNext())
				{
					count = cursor.getString(cursor.getColumnIndex("c"));
				}
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		return count;
	}

	public void savedata(String notificationId, String apiKey, String title, String message, String uri, String notificationType,
			String accountname, String mobilephone, String hospitalcode,String senddate)
	{
		mSQLiteDatabase = context.openOrCreateDatabase("PUSHNOTIFICATION20140804.db", context.MODE_PRIVATE, null);
		// String droptable="drop table WX_PUSH";
		// try {
		// mSQLiteDatabase.execSQL(droptable);
		// } catch (Exception e) {
		// System.out.println(e.getMessage());
		// }

		String createtable = " CREATE TABLE  if not exists WX_PUSH (xh  integer PRIMARY KEY autoincrement , "
				+ " title varchar(100)  ,message varchar(500)  ,apiKey varchar(100)  , "
				+ "uri varchar(100) ,time varchar(30) ,type varchar(30) ,sfbc varchar(30) ,memo varchar(100),"
				+ "accountname varchar(100),mobilephone varchar(100),hospitalcode varchar(100),senddate varchar(100),isshow varchar(100) DEFAULT '0')";

		try
		{
			mSQLiteDatabase.execSQL(createtable);
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		// message = AESTest.encode(Utils.sqliteEscape(message));

		String insert = "INSERT INTO WX_PUSH (title,message,time,type,accountname,mobilephone,hospitalcode,senddate) VALUES ('" + title
				+ "','" + message + "','" + getdatetime() + "','" + notificationType + "','" + accountname + "','" + mobilephone + "','"
				+ hospitalcode + "','"+senddate+"')";
		try
		{
			mSQLiteDatabase.execSQL(insert);
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		mSQLiteDatabase.close();

	}

	private String getdatetime()
	{
		// Date now = new Date();
		// Calendar cal = Calendar.getInstance(Locale.CHINA);
		//
		// DateFormat d1 = DateFormat.getDateTimeInstance();
		// //默认语言（汉语）下的默认风格（MEDIUM风格，比如：2008-6-16 20:54:53）
		// String str1 = d1.format(now);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowTime = format.format(new Date());
		return nowTime;
	}

	private int getNotificationIcon()
	{
		return sharedPrefs.getInt(Constants.NOTIFICATION_ICON, 0);
	}

	private boolean isNotificationEnabled()
	{
		return sharedPrefs.getBoolean(Constants.SETTINGS_NOTIFICATION_ENABLED, true);
	}

	private boolean isNotificationSoundEnabled()
	{
		return sharedPrefs.getBoolean(Constants.SETTINGS_SOUND_ENABLED, true);
	}

	private boolean isNotificationVibrateEnabled()
	{
		return sharedPrefs.getBoolean(Constants.SETTINGS_VIBRATE_ENABLED, true);
	}

	private boolean isNotificationToastEnabled()
	{
		return sharedPrefs.getBoolean(Constants.SETTINGS_TOAST_ENABLED, false);
	}

	public void closeNotification()
	{
		if (notificationManager != null)
		{
			notificationManager.cancelAll();
		}

	}

}
